package edu.tum.cs.stageflow.benchmarkapplications.sobelfilter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SmartFilterExecutor {
	
	private java.awt.image.BufferedImage inputImage;
	private java.awt.image.BufferedImage[] splitImage;
	private int xDev;
	private int yDev;
	
	
	/*	step 1 - read image */
	public boolean readImage(String picturepath) {
		try {
			inputImage = ImageIO.read(new File(picturepath));
		} catch (IOException e) {
			return false;
			//TODO evtl. function throws exception 
		}
		
		return true;
	}
	
	/* step 2 - devide images into subpictures */
	public boolean splitImage(int xDevision, int yDevisions) {
		xDev = xDevision;
		yDev = yDevisions;
		int width = inputImage.getWidth();
		int height = inputImage.getHeight();
		
		splitImage = new BufferedImage[xDev*yDev];
		
		for(int y = 0; y< yDev; y++) {
			for(int x = 0; x < xDev; x++) {
				splitImage[y*xDev + x] = inputImage.getSubimage((width / xDev)*x, 
						(height / xDev)*y, 
						(width / xDev), 
						(height / xDev));
				
			}
		}
		
		return true;
	}
	
	/* step 3 - use sobel filter on partial image */
	public boolean executeFilter(int executorNR) {
		SmartSobelFilter filter = new SmartSobelFilter();
		filter.filter(splitImage[executorNR-1]);
		return true;
	}
	
	/*	step 4 - write image */
	public boolean writeImage(String picturepath) {
		try {
			ImageIO.write(inputImage, "jpg", new File(picturepath));
		} catch (IOException e) {
			return false;
			//TODO evtl. function throws exception 
		}
		
		return true;
	}
	
	//Test Main :-)
	public static void main(String[] args) {
		SmartFilterExecutor executor = new SmartFilterExecutor(); 
		executor.readImage("f://Lars.jpg");
		executor.splitImage(1,1);
		executor.executeFilter(1);
		executor.writeImage("f://Lars_sobeled.jpg");
		System.out.println("Finish.");
	}
	
	 /*public static void main(String[] args) {
		  	System.out.println("Starting Here");
			SobelFilter filter = new SobelFilter();
			try {
				new edu.tum.cs.stageflow.executionframework.StageRunner(filter);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Done");
	}*/
	
}
